/**
 * 文件名称:  ParamSetServiceImpl.java
 * 文件序号:  序号
 * 内容描述:  业务参数设置service实现类
 * 版权声明:  山东鸿蝶信息技术有限公司
 * 创建用户:  MissJin
 * 创建日期:  2017/1/18/17:23
 * 修改用户:  无
 * 修改日期:  无
 * 修改说明:  无
 * 文件版本:  V1.0
 * 文件路径:
 */
package com.hongdee.base.param.service.impl;


import com.hongdee.base.param.dao.IParamSetDao;
import com.hongdee.base.param.entity.ParamSet;
import com.hongdee.base.param.service.IParamSetService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.hongdee.base.Constant.P_ROOT_ID;

/**
 * 名  称: ParamSetServiceImpl
 * 类  型: class
 * 描  述: 业务参数设置service实现类
 * 路  径: com.hongdee.base.param.service.impl
 * 作  者: MissJin
 * 日  期: 2017/1/18/17:24
 */
@Service
public class ParamSetServiceImpl implements IParamSetService {
    private String tabName = "T_BC_PARAM_SET";
    /**
     * 存放已选择的参数列表
     */
    private Map<String, String> chekedMap = null;
    @Autowired
    private IParamSetDao iParamSetDao;

    /**
     * @param id      部门
     * @param sysCode 模块
     * @param defType 参数类型
     * @return Map
     * @throws Exception
     * @desc 查询参数值
     * @author 徐钦勇
     */
    @Override
    public List<Map<String, Object>> info(String id, String defType, String sysCode) throws Exception {

        return null;
    }


    @Override
    public void save(List<Map<String, Object>> nodes, String companyId) throws Exception {
        //遍历节点保存
        System.out.println("节点");

        chekedMap = paramMap(companyId);
        ParamSet paramSet;
        List<String> existKeys = new ArrayList<>();
        //取得要保存的节点，仅保留参数
        for (Map<String, Object> node : nodes) {
            String type = String.valueOf(node.get("type"));
            if (!"0".equals(type)) {
                //参数类型
                //编码判断
                String key = String.valueOf(node.get("id"));
                existKeys.add(key);
                if (!chekedMap.containsKey(key)) {
                    //新增的节点
                    paramSet = new ParamSet();
                    paramSet.setDefId(key);
                    paramSet.setName(String.valueOf(node.get("name")));
                    paramSet.setCode(String.valueOf(node.get("code")));
                    paramSet.setpCode(String.valueOf(node.get("pCode")));
                    paramSet.setValueType(String.valueOf(node.get("valueType")));
                    paramSet.setValue(String.valueOf(node.get("defValue")));
                    paramSet.setCompanyId(companyId);
                    this.iParamSetDao.saveOrUpdate(paramSet);
                    //保存
                }
            }
        }

        //删除不在需要的节点
        StringBuffer delSql = new StringBuffer("delete from t_bc_param_set where company_id = ? and def_id not in (");

        for (String s : existKeys) {
            delSql.append("?,");
        }
        delSql.append(" '')");
        existKeys.add(0, companyId);
        this.iParamSetDao.executeSQL(delSql.toString(), existKeys.toArray());

    }

    /**
     * @param start     当前页码
     * @param limit     页面大小
     * @param pCode     上级编码
     * @param companyId 公司 ID
     * @return Map
     * @throws Exception
     * @desc page分页查询
     * @author 徐钦勇
     */
    @Override
    public Map page(String start, String limit, String pCode, String companyId) throws Exception {
        String sql = "select * from " + tabName + " where p_code = ? and company_id =?";
        List params = new ArrayList();
        params.add(pCode);
        params.add(companyId);
        return this.iParamSetDao.page(sql, params.toArray(), start, limit);
    }

    /**
     * 查询参数定义树
     *
     * @return
     */
    @Override
    public List defTree() throws Exception {
        return buildParamDefChild(P_ROOT_ID);
    }

    private List buildParamDefChild(String key) throws Exception {
        //从缓存中取得用户已有的角色

        String sqlStr = " select * from t_bc_param_def where p_code = ? and status='1' ";
        List<Map<String, Object>> treeP = this.iParamSetDao.list(sqlStr, key);
        return buildParamDefParent(treeP);
    }

    private List buildParamDefParent(List<Map<String, Object>> paramList) throws Exception {
        if (paramList.size() == 0) {
            return paramList;
        }
        List<Map<String, Object>> childList;
        for (Map map : paramList) {
            String resId = String.valueOf(map.get("code"));
            childList = buildParamDefChild(resId);
            //存在子节点，增加子节点 返回
            map.put("child", childList);
        }
        return paramList;
    }

    /**
     * 查询当前单位的设置参数树
     *
     * @param companyId
     * @return
     * @throws Exception
     */
    @Override
    public List setTree(String companyId,String pCode) throws Exception {

        if (StringUtils.isEmpty(companyId)) {
            throw new Exception("请选择公司！");
        }
        chekedMap = paramMap(companyId);
        String rootId=P_ROOT_ID;
        if(!"".equals(pCode)){
            rootId=pCode;
        }
        return buildParamSetChild(rootId);
    }

    private List buildParamSetChild(String key) throws Exception {
        //从缓存中取得用户已有的角色

        String sqlStr = " select * from t_bc_param_def where p_code = ? and status='1' ";
        List<Map<String, Object>> treeP = this.iParamSetDao.list(sqlStr, key);
        return buildParamSetParent(treeP);
    }

    private List buildParamSetParent(List<Map<String, Object>> paramList) throws Exception {
        if (paramList.size() == 0) {
            return paramList;
        }

        List<Map<String, Object>> treeList = new ArrayList<>();
        List<Map<String, Object>> childList;
        List<Map<String, Object>> tempChildList;
        for (Map map : paramList) {

            String resId = String.valueOf(map.get("code"));
            childList = buildParamSetChild(resId);
            if (childList.size() == 0) {
                String key = String.valueOf(map.get("id"));
                if (chekedMap.containsKey(key)) {
                    treeList.add(map);
                    continue;
                }
            } else {
                tempChildList = new ArrayList<>();
                String type = "";
                for (Map<String, Object> childMap : childList) {
                    type = String.valueOf(childMap.get("type"));
                    if ("0".equals(type)) {
                        tempChildList.add(childMap);
                    }
                }
                map.put("child", tempChildList);
                treeList.add(map);


            }

        }
        return treeList;
    }

    /**
     * 获取当前公司选中的参数
     *
     * @param companyId 公司 ID
     * @return 参数集合
     * @throws Exception
     */
    private Map<String, String> paramMap(String companyId) throws Exception {
        String sqlStr = "select def_id, code,p_code from " + tabName + " where company_id = ?";
        List<Map<String, Object>> lsMp = this.iParamSetDao.list(sqlStr, companyId);
        Map<String, String> temp = new HashMap();
        for (Map<String, Object> mp : lsMp) {
            temp.put(String.valueOf(mp.get("defId")), companyId);
        }
        return temp;
    }

    /**
     * 取得已选择中的参数节点
     *
     * @param companyId
     * @return
     * @throws Exception
     */
    @Override
    public List<Object> checkedDef(String companyId) throws Exception {
        String sqlStr = "select def_id, code,p_code from " + tabName + " where company_id = ?";
        List<Map<String, Object>> lsMp = this.iParamSetDao.list(sqlStr, companyId);
        List<Object> temp = new ArrayList<>();
        for (Map<String, Object> mp : lsMp) {
            temp.add(mp.get("defId"));
        }
        return temp;
    }

    /**
     * 修改默认值
     *
     * @param id
     * @param value
     * @throws Exception
     */
    @Override
    public void changValue(String id, String value) throws Exception {

        String hql = "update ParamSet set value =:value where id =:id";
        Map<String, Object> params = new HashMap<>();
        params.put("value", value);
        params.put("id", id);
        this.iParamSetDao.update(hql, params);
    }

}
